<template>
  <el-row :gutter="20" class="admin-container">
    <!-- 主内容区域 -->
    <el-col :span="24">
      <!-- 页面头部 -->
      <el-row :gutter="10" class="admin-header">
        <el-col :span="24" :sm="16">
          <h2>文章管理</h2>
        </el-col>
        <el-col :span="24" :sm="8" class="text-right">
          <el-button type="primary" @click="showCreateForm = true" class="create-btn">
            <el-icon><Plus /></el-icon>
            新增文章
          </el-button>
        </el-col>
      </el-row>
      
      <!-- 文章列表 -->
      <div class="article-table">
        <el-table :data="articles" style="width: 100%" :max-height="isMobile ? '400px' : '600px'">
          <el-table-column prop="id" label="ID" width="80" :show="!isMobile" />
          <el-table-column prop="title" label="标题" min-width="300">
            <template #default="scope">
              <router-link :to="'/article/' + scope.row.id" target="_blank" class="article-title-link">
                {{ scope.row.title }}
              </router-link>
            </template>
          </el-table-column>
          <el-table-column prop="category" label="分类" width="120" :show="!isMobile" />
          <el-table-column prop="createTime" label="创建时间" width="180" :formatter="formatDate" :show="!isMobile" />
          <el-table-column prop="updateTime" label="更新时间" width="180" :formatter="formatDate" />
          <el-table-column label="操作" width="120" fixed="right" align="center">
            <template #default="scope">
              <div class="table-actions">
                <el-button type="primary" size="small" @click="editArticle(scope.row)" circle>
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button type="danger" size="small" @click="deleteArticle(scope.row.id)" circle>
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pageInfo.pageNum"
          v-model:page-size="pageInfo.pageSize"
          :page-sizes="[10, 20, 50]"
          :layout="isMobile ? 'prev, pager, next' : 'total, sizes, prev, pager, next, jumper'"
          :total="pageInfo.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="pagination-container"
        />
      </div>
    </el-col>
    
    <!-- 创建/编辑文章对话框 -->
    <el-dialog
      v-model="showCreateForm"
      :title="editingArticle ? '编辑文章' : '创建文章'"
      :width="isMobile ? '95%' : '80%'"
      :before-close="handleCloseDialog"
      center
      destroy-on-close
    >
      <el-form
        ref="articleFormRef"
        :model="articleForm"
        :rules="rules"
        :label-width="isMobile ? '80px' : '100px'"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="articleForm.title" placeholder="请输入文章标题" :maxlength="200" show-word-limit />
        </el-form-item>
        
        <el-form-item label="分类" prop="category">
          <el-input v-model="articleForm.category" placeholder="请输入文章分类" :maxlength="50" />
        </el-form-item>
        
        <el-form-item label="内容" prop="content">
          <div class="editor-container" :class="{ 'mobile-editor': isMobile }">
            <!-- 这里可以集成 md-editor-v3 编辑器 -->
            <el-input
              v-model="articleForm.content"
              type="textarea"
              placeholder="请输入文章内容"
              :rows="isMobile ? 10 : 15"
            />
          </div>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-radio-group v-model="articleForm.status" :class="{ 'mobile-radio': isMobile }">
            <el-radio :label="1">已发布</el-radio>
            <el-radio :label="0">草稿</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-space>
          <el-button @click="handleCloseDialog">取消</el-button>
          <el-button type="primary" @click="saveArticle" :loading="saving">保存</el-button>
        </el-space>
      </template>
    </el-dialog>
  </el-row>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useArticleStore } from '@/store/articleStore'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'

export default {
  name: 'Admin',
  components: {
    Plus,
    Edit,
    Delete
  },
  setup() {
    const router = useRouter()
    const articleStore = useArticleStore()
    const articles = ref([])
    const loading = ref(false)
    const saving = ref(false)
    const showCreateForm = ref(false)
    const editingArticle = ref(null)
    const articleFormRef = ref(null)
    const isMobile = ref(false)
    
    const pageInfo = reactive({
      pageNum: 1,
      pageSize: 10,
      total: 0
    })
    
    const articleForm = reactive({
      title: '',
      category: '',
      content: '',
      status: 1
    })
    
    const rules = {
      title: [
        { required: true, message: '请输入文章标题', trigger: 'blur' },
        { min: 2, max: 200, message: '标题长度应在 2 到 200 个字符之间', trigger: 'blur' }
      ],
      content: [
        { required: true, message: '请输入文章内容', trigger: 'blur' }
      ]
    }

    // 获取文章列表
    const fetchArticles = async () => {
      loading.value = true
      try {
        const result = await articleStore.fetchArticlePage(pageInfo.pageNum, pageInfo.pageSize)
        articles.value = result?.records || []
        pageInfo.total = result?.totalRow || 0
      } catch (error) {
        ElMessage.error('获取文章列表失败')
        console.error('获取文章列表失败:', error)
      } finally {
        loading.value = false
      }
    }

    // 格式化日期
    const formatDate = (row, column) => {
      const date = new Date(row[column.property])
      return date.toLocaleString('zh-CN')
    }

    // 处理每页条数变化
    const handleSizeChange = (size) => {
      pageInfo.pageSize = size
      pageInfo.pageNum = 1
      fetchArticles()
    }

    // 处理页码变化
    const handleCurrentChange = (current) => {
      pageInfo.pageNum = current
      fetchArticles()
    }

    // 重置表单
    const resetForm = () => {
      articleForm.title = ''
      articleForm.category = ''
      articleForm.content = ''
      articleForm.status = 1
      if (articleFormRef.value) {
        articleFormRef.value.resetFields()
      }
    }

    // 打开创建文章表单
    const openCreateForm = () => {
      editingArticle.value = null
      resetForm()
      showCreateForm.value = true
    }

    // 编辑文章
    const editArticle = (article) => {
      editingArticle.value = article
      articleForm.title = article.title
      articleForm.category = article.category
      articleForm.content = article.content
      articleForm.status = article.status || 1
      showCreateForm.value = true
    }

    // 关闭对话框
    const handleCloseDialog = () => {
      showCreateForm.value = false
      setTimeout(() => {
        resetForm()
        editingArticle.value = null
      }, 300)
    }

    // 保存文章
    const saveArticle = async () => {
      if (!articleFormRef.value) return
      
      try {
        await articleFormRef.value.validate()
        saving.value = true
        
        const formData = {
          title: articleForm.title,
          category: articleForm.category,
          content: articleForm.content,
          status: articleForm.status
        }
        
        if (editingArticle.value) {
          // 更新文章
          await articleStore.updateArticle(editingArticle.value.id, formData)
          ElMessage.success('文章更新成功')
        } else {
          // 创建文章
          await articleStore.createArticle(formData)
          ElMessage.success('文章创建成功')
        }
        
        handleCloseDialog()
        fetchArticles() // 重新加载列表
      } catch (error) {
        ElMessage.error(error.message || '保存失败')
        console.error('保存文章失败:', error)
      } finally {
        saving.value = false
      }
    }

    // 删除文章
    const deleteArticle = (id) => {
      ElMessageBox.confirm('确定要删除这篇文章吗？', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await articleStore.deleteArticle(id)
          ElMessage.success('删除成功')
          fetchArticles() // 重新加载列表
        } catch (error) {
          ElMessage.error(error.message || '删除失败')
        }
      }).catch(() => {
        // 取消删除
      })
    }
    
    // 检查是否为移动设备
    const checkIsMobile = () => {
      isMobile.value = window.innerWidth <= 768
    }
    
    // 监听窗口大小变化
    onMounted(() => {
      checkIsMobile()
      window.addEventListener('resize', checkIsMobile)
      fetchArticles()
    })
    
    onUnmounted(() => {
      window.removeEventListener('resize', checkIsMobile)
    })

    return {
      articles,
      loading,
      saving,
      showCreateForm,
      editingArticle,
      articleFormRef,
      articleForm,
      rules,
      pageInfo,
      isMobile,
      formatDate,
      handleSizeChange,
      handleCurrentChange,
      handleCloseDialog,
      editArticle,
      saveArticle,
      deleteArticle
    }
  }
}
</script>

<style scoped>
.admin-container {
  padding: 20px;
}

/* 页面头部样式 */
.admin-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.admin-header h2 {
  font-size: 1.8rem;
  margin: 0;
  color: #2c3e50;
}

.create-btn {
  width: 100%;
}

/* 文章表格样式 */
.article-table {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.article-title-link {
  color: #333;
  text-decoration: none;
  transition: color 0.3s;
}

.article-title-link:hover {
  color: #1890ff;
}

.table-actions {
  display: flex;
  gap: 8px;
  justify-content: center;
}

/* 分页样式 */
.pagination {
  margin-top: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 编辑器容器样式 */
.editor-container {
  min-height: 400px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.editor-container.mobile-editor {
  min-height: 300px;
}

/* 单选框组样式 */
.mobile-radio {
  display: flex;
  justify-content: space-around;
}

/* Element Plus 表格优化 */
:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table__cell) {
  padding: 8px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .admin-container {
    padding: 15px;
  }
}

@media (max-width: 992px) {
  .admin-header h2 {
    font-size: 1.6rem;
  }
}

@media (max-width: 768px) {
  .admin-container {
    padding: 10px;
  }
  
  .admin-header {
    padding-bottom: 10px;
  }
  
  .admin-header h2 {
    font-size: 1.5rem;
    margin-bottom: 10px;
  }
  
  .article-table {
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  }
  
  .editor-container {
    min-height: 300px;
  }
  
  .editor-container.mobile-editor {
    min-height: 250px;
  }
  
  :deep(.el-table__cell) {
    padding: 6px;
  }
  
  :deep(.el-input__wrapper) {
    font-size: 14px;
  }
  
  :deep(.el-form-item__label) {
    font-size: 14px;
  }
  
  /* 表格操作按钮样式优化 */
  .table-actions .el-button--small {
    width: 32px;
    height: 32px;
    padding: 0;
  }
  
  /* 对话框表单元素间距优化 */
  :deep(.el-form-item) {
    margin-bottom: 16px;
  }
}

@media (max-width: 480px) {
  .admin-container {
    padding: 0 10px;
  }
  
  .admin-header h2 {
    font-size: 1.3rem;
  }
  
  :deep(.el-table) {
    font-size: 12px;
  }
  
  :deep(.el-table__cell) {
    padding: 4px 2px;
  }
  
  .editor-container {
    min-height: 250px;
  }
  
  .editor-container.mobile-editor {
    min-height: 200px;
  }
  
  /* 按钮样式优化 */
  .table-actions {
    gap: 4px;
  }
  
  .table-actions .el-button--small {
    width: 28px;
    height: 28px;
  }
  
  /* 输入框样式优化 */
  :deep(.el-input__wrapper) {
    font-size: 13px;
    padding: 0 8px;
  }
  
  :deep(.el-form-item__label) {
    font-size: 13px;
  }
  
  /* 对话框按钮样式优化 */
  :deep(.el-dialog__footer .el-space) {
    width: 100%;
  }
  
  :deep(.el-dialog__footer .el-button) {
    flex: 1;
  }
}

/* 适配平板横屏 */
@media (min-width: 769px) and (max-width: 1024px) {
  .admin-header h2 {
    font-size: 1.5rem;
  }
  
  .article-table {
    box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
  }
}
</style>